"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--磁盘
Case Name   : 慢盘（磁盘I/O速度变慢）
Create At   : 2020-12-29
Owner       : n@ningyali
Description :
    1、DN主注入故障
        ./cfe "inject rdisk(fault,dev,ms,freq,count,lba,endlba)values(ds,/dev/sdb,100000,100,400,0,0xFFFF)"
    2、查询故障是否注入成功
        ./cfe "query  rdisk "
    3、对数据库进行dml操作
    4、清除故障
        ./cfe "clean  rdisk"
    5、对数据库进行dml操作
Expect      :
    1、故障注入成功
    2、dml操作变慢，但可以成功
    3、清除故障成功
    4、dml操作速度恢复正常
History     :
"""

import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.Common import *
from testcase.utils.CommonSH import *


class PrimaryNodeInjectDs(unittest.TestCase):
    primary_sh = CommonSH('PrimaryDbUser')
    standby1_sh = CommonSH('Standby1DbUser')
    standby2_sh = CommonSH('Standby2DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------reliability_hardware019:开始执行------------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.com = Common()
        self.Constant = Constant()
        self.t_name = 'test_hardware019'

        self.log.info("---------------获取DN主磁盘名----------------")
        shell_cmd = f"df -h {macro.DB_INSTANCE_PATH}"
        self.log.info(shell_cmd)
        result = self.primary_root_node.sh(shell_cmd).result()
        self.disk_name = result.splitlines()[-1].split()[0].strip()
        self.log.info('result: ' + result + '\n' + 'disk_name: ' + self.disk_name)

    def test_main(self):
        self.log.info("---------------建表----------------")
        create_table_cmd = f'''drop table if exists {self.t_name}; 
                            create table {self.t_name}(id int,name varchar(50),name1 varchar(50),name2 varchar(50));'''
        self.log.info(create_table_cmd)
        msg = self.primary_sh.executDbSql(create_table_cmd)
        self.log.info(msg)
        self.assertIn(self.Constant.CREATE_TABLE_SUCCESS, msg)

        self.log.info("---------------获取磁盘扇区个数----------------")
        shell_cmd = f"fdisk -l {self.disk_name}"
        self.log.info(shell_cmd)
        msg = self.primary_root_node.sh(shell_cmd).result()
        sectors = msg.splitlines()[0].split(',')[-1].split()[0].strip()
        self.log.info('result: ' + msg + '\n' + 'sectors: ' + sectors)

        self.log.info("---------------DN主注入故障----------------")
        endlba = len(hex(int(sectors))) * 'F'
        shell_cmd = f'''{macro.CFE_PATH}/cfe 'inject rdisk(fault,dev,ms,freq,count,lba,endlba)values(ds,{self.disk_name},60000,100,400,0,0x{endlba})' '''
        self.log.info(shell_cmd)
        msg = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        self.assertIn(self.Constant.CFE_INJECT_RDISK_SUCCESS_MSG, msg)

        time.sleep(10)

        self.log.info("-------------查询故障是否注入成功---------------")
        shell_cmd = f'''{macro.CFE_PATH}/cfe 'query  rdisk' | grep {self.disk_name} | grep ds '''
        self.log.info(shell_cmd)
        msg = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        self.assertTrue(len(msg) > 0)

        self.log.info("-------------对数据库进行dml操作，并计算执行时间---------------")
        start_time = time.time()
        insert_cmd = f"insert into {self.t_name} values (generate_series(1,100000), '测试1', '注入故障后执行dml', '持续写入数据');	"
        dml_result = self.primary_sh.executDbSql(insert_cmd)
        self.log.info('sqlexecute result: ' + dml_result)
        for error_msg in self.Constant.SQL_WRONG_MSG:
            self.assertNotIn(error_msg, msg)

        exec_dml_time_with_faulted = time.time() - start_time
        self.log.info(exec_dml_time_with_faulted)

        self.log.info("---------------清除故障----------------")
        shell_cmd = f'''{macro.CFE_PATH}/cfe 'clean  rdisk' '''
        self.log.info(shell_cmd)
        msg = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        self.assertIn(self.Constant.CFE_CLEAN_RDISK_SUCCESS_MSG, msg)

        time.sleep(60)

        self.log.info("-------------查看集群状态---------------")
        db_status = self.primary_sh.getDbClusterStatus('status')
        self.assertTrue(db_status)

        self.log.info("-------------对数据库进行dml操作，并计算执行时间---------------")
        start_time_1 = time.time()
        insert_cmd = f"insert into {self.t_name} values (generate_series(1,100000), '测试1', '注入故障后执行dml', '持续写入数据');	"
        dml_result = self.primary_sh.executDbSql(insert_cmd)
        self.log.info('sqlexecute result: ' + dml_result)
        for error_msg in self.Constant.SQL_WRONG_MSG:
            self.assertNotIn(error_msg, msg)

        exec_dml_time_without_faulted = time.time() - start_time_1
        self.log.info(exec_dml_time_without_faulted)
        self.assertLess(exec_dml_time_without_faulted, exec_dml_time_with_faulted)

    def tearDown(self):
        self.log.info("---------------清除故障----------------")
        shell_cmd = f'''{macro.CFE_PATH}/cfe 'clean  rdisk' '''
        self.log.info(shell_cmd)
        msg = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        self.log.info('------------reliability_hardware019:执行完成------------')
